package com.zee.wechat.module.menu.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zee.wechat.module.menu.mapper.MenuMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
public class MenuService {
    @Resource
    private MenuMapper menuDao;
    @Autowired
    private CreatWechatMenuService creatWechatMenuService;

    public void addMenu(Map<String, Object> param) {
        menuDao.addMenu(param);
    }

    public void addSubMenu(Map<String, Object> param) {
        menuDao.addSubMenu(param);
    }

    @Transactional(rollbackFor = Exception.class)
    public List<Map<String, Object>> queryMenus(String wechatId) {
        List<Map<String, Object>> menus = menuDao.queryMenus(wechatId);
        if (CollectionUtils.isEmpty(menus)) {
            //通过Api获取菜单
            return getMenuByApi(wechatId);
        } else {
            for (Map<String, Object> map : menus) {
                map.put("subMenus", menuDao.querySubMenus(String.valueOf(map.get("code"))));
            }
        }
        return menus;
    }

    public List<Map<String, Object>> getMenuByApi(String wechatId) {
        // 查询公众号appID 和APPsercret
        Map<String, Object> wechat = queryWechatInfoById(wechatId);
        JSONObject json = creatWechatMenuService.getWechatAccessToken(
                String.valueOf(wechat.get("app_id")),
                String.valueOf(wechat.get("app_secret")));
        List<Map<String, Object>> menus = new ArrayList<>();
        try {
            String result = creatWechatMenuService.getMenuList(
                    json.getString("access_token"));
            JSONObject menusResult = JSONObject.parseObject(result);
            JSONObject menu = menusResult.getJSONObject("selfmenu_info");
            JSONArray buttons = menu.getJSONArray("button");
            for (int i = 0; i < buttons.size(); i++) {
                JSONObject button = buttons.getJSONObject(i);
                JSONObject subButtonObj = button.getJSONObject("sub_button");
                String uuid = "menu_" + UUID.randomUUID().toString();
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("name", button.getString("name"));
                param.put("code", uuid);
                param.put("wechatId", wechatId);
                param.put("mType", button.getString("type"));
                if (Objects.nonNull(subButtonObj)) {
                    JSONArray subButtons = subButtonObj.getJSONArray("list");
                    List<Map<String, Object>> subMenus = new ArrayList<>();
                    for (int j = 0; j < subButtons.size(); j++) {
                        JSONObject subButton = subButtons.getJSONObject(j);
                        Map<String, Object> subParam = new HashMap<String, Object>();
                        String subCode = "subMenu_" + UUID.randomUUID().toString();
                        subParam.put("name", subButton.getString("name"));
                        subParam.put("sType", subButton.getString("type"));
                        subParam.put("code", uuid);
                        subParam.put("subCode", subCode);
                        if ("view".equals(subButton.getString("type"))) {
                            subParam.put("url", subButton.getString("url"));
                        } else {
                            subParam.put("key", subButton.getString("key"));
                        }
                        subMenus.add(subParam);
                        this.addSubMenu(subParam);
                    }
                    param.put("subMenus", subMenus);
                    param.put("hasSubMenu", "no");
                } else {

                    if ("view".equals(button.getString("type"))) {
                        param.put("url", button.getString("url"));
                    } else {
                        param.put("key", button.getString("key"));
                    }
                    param.put("subMenus", new HashMap<>());
                    param.put("hasSubMenu", "yes");
                }
                this.addMenu(param);
                menus.add(param);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return menus;
    }

    public void deleteMenu(String menuCode) {
        menuDao.deleteMenu(menuCode);
    }

    public void deleteSubMenu(String menuCode) {
        menuDao.deleteSubMenu(menuCode);
    }

    public Map<String, Object> queryMenuByCode(
            @Param(value = "menuCode") String menuCode) {
        return menuDao.queryMenuByCode(menuCode);
    }

    public Map<String, Object> querySubMenuByCode(
            @Param(value = "menuCode") String menuCode) {
        return menuDao.querySubMenuByCode(menuCode);
    }

    public void deleteAllSubMenu(@Param(value = "menuCode") String menuCode) {
        menuDao.deleteAllSubMenu(menuCode);
    }

    public void updateMenu(Map<String, String> param) {
        menuDao.updateMenu(param);
    }

    public void updateSubMenu(Map<String, String> param) {
        menuDao.updateSubMenu(param);
    }

    public Map<String, Object> queryWechatInfoById(String wechatId) {
        return menuDao.queryWechatInfoById(wechatId);
    }

    public void updateMenuHasSubMenu(String hasSubMenu, String menuCode) {
        menuDao.updateMenuHasSubMenu(hasSubMenu, menuCode);
    }
}
